package com.ikun.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ikun.pojo.Result;
import com.ikun.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器
 * */

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    /**
     * 目标资源方法运行前运行，放行返回true，不放行返回false
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求路径的url
        String url = request.getRequestURI();
        System.out.println("接收到的url为:"+url);
        //2.判断url中是不是包含login,如果是，则放行
        if (url.contains("login")||url.contains("avatar")) {
            return true;
        }
        //3.获取请求头中的令牌(token)
        String token = request.getHeader("token");
        //4.判断令牌是否存在，不存在则返回错误信息：未登录
        if (!StringUtils.hasLength(token)) {
            System.out.println("为空token(令牌不存在)");
            Result error = Result.error("NO_LOGIN");
            //手动将error转化为json格式的字符串,用的是外部库:alibaba
            String noLong = JSONObject.toJSONString(error);
            response.getWriter().write(noLong);
            return false;
        }
        //5.解析token，如果解析失败，返回错误信息(未登录)
        boolean isRight = JwtUtil.parseJwt(token);
        if (isRight) {
            return true;
        } else {
            System.out.println("token 解析失败");
            Result error = Result.error("NO_LOGIN");
            //手动将error转化为json格式的字符串,用的是外部库:alibaba
            String noLong = JSONObject.toJSONString(error);
            response.getWriter().write(noLong);
            return false;
        }
    }
    /**
     * 目标资源方法运行后，返回视图前运行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 目标资源方法运行后，返回视图后运行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

